package cn.rkylin.oms.warehouse.stock.service;

import cn.rkylin.oms.goods.domain.GoodsSku;
import cn.rkylin.oms.goods.service.IGoodsService;
import cn.rkylin.oms.system.stockpush.domain.StockFmla;
import cn.rkylin.oms.system.stockpush.service.IStockPushService;
import cn.rkylin.oms.system.storage.domain.Stor;
import cn.rkylin.oms.system.storage.service.IStorService;
import cn.rkylin.oms.warehouse.stock.dao.IStockDAO;
import cn.rkylin.oms.warehouse.stock.domain.BatchStockLog;
import cn.rkylin.oms.warehouse.stock.domain.Stock;
import cn.rkylin.oms.warehouse.stock.domain.StockLog;
import cn.rkylin.oms.warehouse.stock.vo.BatchStockVO;
import cn.rkylin.oms.warehouse.stock.vo.StockVO;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 库存服务实现类
 *
 * @author liming
 * @date 2017/10/16
 */
@Service("stockService")
public class StockServiceImpl implements IStockService {

    @Autowired
    private IStockDAO stockDAO;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IStorService storService;

    @Autowired
    private IStockPushService stockPushService;

    //@Autowired
    //ProjectManagerService projectService;

    /**
     * 获取库存信息
     *
     * @param entId
     * @param skuId
     * @param storId
     * @return StockVO
     * @throws Exception
     */
    @Override
    public StockVO getStock(String entId, String prjId, String skuId, String storId) throws Exception {
        StockVO param = new StockVO();
        param.setEntId(entId);
        param.setSkuId(skuId);
        param.setStorId(storId);
        StockVO stockVO = stockDAO.getStock(param);

        // 可分派数
        if (stockVO != null) {
            StockFmla fmla = stockPushService.getStockFmlaByProjectId(prjId);

            if (fmla != null) {
                if (fmla.getStockValMode().equalsIgnoreCase("local")) {
                    // 第三方库存数使用本地计算：可分派数 = 库存数(stock_qty) - 已分派数- 预留数- 冻结数-
                    // 逻辑出库数
                    stockVO.setCanallotQty(stockVO.getStockQty() - stockVO.getAllotQty() - stockVO.getReserveQty() - stockVO.getFreezeQty()
                            - stockVO.getLogicStockoutQty());
                    // 残次品可分派数
                    stockVO.setJunkCanallotQty(stockVO.getJunkQty() - stockVO.getJunkAllotQty());
                } else {
                    // 第三方库存数使用实际仓储：可分派数 = 库存数(sell_count) - 已分派数- 预留数 - 冻结数
                    stockVO.setCanallotQty(stockVO.getSellCount() - stockVO.getAllotQty() - stockVO.getReserveQty() - stockVO.getFreezeQty());
                    // 残次品可分派数
                    stockVO.setJunkCanallotQty(stockVO.getJunkCount() - stockVO.getJunkAllotQty());
                }
            }
        }
        return stockVO;
    }

    @Override
    public List<StockVO> getSkuList(StockVO stockVO) throws Exception {
        return stockDAO.getSkuList(stockVO);
    }

    /**
     * 更新库存
     *
     * @param stockVO 必填属性 stockVO(storId,endId,skuId,sourceId)
     * @return 影响行数
     * @throws Exception
     */
    @Override
    public int updateStock(StockVO stockVO) throws Exception {
    	/*String dockingKingdee = projectService.getCurrentPrjDockingKingdee();
		// 非金蝶项目
		if ("y".equals(dockingKingdee)) {
			return 1;
		}*/

        // sku相关属性
        GoodsSku sku = goodsService.getGoodsSkuBySkuId(stockVO.getSkuId());

        stockVO.setGoodsId(sku.getGoodsId());
        stockVO.setGoodsCode(sku.getGoodsCode());
        stockVO.setGoodsName(sku.getGoodsName());
        stockVO.setSkuCode(sku.getSkuCode());
        stockVO.setSkuName(sku.getSkuName());

        // 仓库相关属性
        Stor stor = storService.selectStorDetail(stockVO.getStorId());
        stockVO.setStorCode(stor.getStorCode());
        stockVO.setStorName(stor.getStorName());

        Stock stock = new Stock();
        BeanUtils.copyProperties(stockVO, stock);

        // 如果库存表里不存在，就新增一条
        int stockEffectRowCount = 0;
        // 获取库存
        StockVO oldStock = stockDAO.getStock(stockVO);
        if (oldStock == null) {
            stockEffectRowCount = insertStock(stock);
        } else {
            stockEffectRowCount = stockDAO.updateStock(stock);
        }

        if (stockEffectRowCount <= 0) {
            return 0;
        }

        // 记录库存日志
        StockLog stockLog = new StockLog();
        stockLog.setLogId(java.util.UUID.randomUUID().toString().replace("-", ""));
        BeanUtils.copyProperties(stockVO, stockLog);
        int stockLogEffectRowCount = insertStockLog(stockLog);

        if (stockLogEffectRowCount <= 0) {
            return 0;
        }
        return 1;
    }

    @Override
    public int updateStock2(StockVO stockVO) throws Exception {
    	/*String dockingKingdee = projectService.getCurrentPrjDockingKingdee();
		// 非金蝶项目
		if ("y".equals(dockingKingdee)) {
			return 1;
		}*/

        // sku相关属性
        GoodsSku sku = goodsService.getGoodsSkuBySkuId(stockVO.getSkuId());

        stockVO.setGoodsId(sku.getGoodsId());
        stockVO.setGoodsCode(sku.getGoodsCode());
        stockVO.setGoodsName(sku.getGoodsName());
        stockVO.setSkuCode(sku.getSkuCode());
        stockVO.setSkuName(sku.getSkuName());

        // 仓库相关属性
        Stor stor = storService.selectStorDetail(stockVO.getStorId());
        stockVO.setStorCode(stor.getStorCode());
        stockVO.setStorName(stor.getStorName());

        Stock stock = new Stock();
        BeanUtils.copyProperties(stockVO, stock);

        // 如果库存表里不存在，就新增一条
        int stockEffectRowCount = 0;
        // 获取库存
        StockVO oldStock = stockDAO.getStock(stockVO);
        if (oldStock == null) {
            stockEffectRowCount = insertStock(stock);
        } else {
            stockEffectRowCount = stockDAO.updateStock2(stock);
        }

        if (stockEffectRowCount <= 0) {
            return 0;
        }

        return 1;
    }

    /**
     * 插入库存
     *
     * @param stock
     * @return
     * @throws Exception
     */
    private int insertStock(Stock stock) throws Exception {

        int effectRowCount = stockDAO.insertStock(stock);
        return effectRowCount;
    }

    /**
     * 插入库存日志
     *
     * @param stockLog
     * @return
     * @throws Exception
     */
    @Override
    public int insertStockLog(StockLog stockLog) throws Exception {
        return stockDAO.insertStockLog(stockLog);
    }

    /**
     * 获取未分派数
     *
     * @param entId
     * @param skuId
     * @param storId
     * @return
     */
    @Override
    public int getUnallotQty(String entId, String skuId, String storId) throws Exception {
        StockVO param = new StockVO();
        param.setEntId(entId);
        param.setSkuId(skuId);
        param.setStorId(storId);
        StockVO stockVO = stockDAO.getUnallotQty(param);
        if (stockVO != null) {
            return stockVO.getUnallotQty();
        } else {
            return 0;
        }
    }

    /**
     * 获取未付款数
     *
     * @param shopId
     * @param skuId
     * @return
     */
    @Override
    public int getUnpayQty(String shopId, String skuId) {
        return 0;
    }

    /**
     * queryStockList：根据查询条件获取库存信息列表
     */
    public PageInfo<StockVO> queryStockList(int page, int length, StockVO queryParamVO) throws Exception {
        return stockDAO.selectPagedByCondition(page, length, queryParamVO);
    }

    /**
     * 更新批次库存（增量）
     *
     * @param stockVO
     * @return
     * @throws Exception
     */
    @Override
    public int updateBatchStock(BatchStockVO stockVO) throws Exception {
        // sku相关属性
        GoodsSku sku = goodsService.getGoodsSkuBySkuId(stockVO.getSkuId());

        stockVO.setGoodsId(sku.getGoodsId());
        stockVO.setGoodsCode(sku.getGoodsCode());
        stockVO.setGoodsName(sku.getGoodsName());
        stockVO.setSkuCode(sku.getSkuCode());
        stockVO.setSkuName(sku.getSkuName());

        // 仓库相关属性
        Stor stor = storService.selectStorDetail(stockVO.getStorId());
        stockVO.setStorCode(stor.getStorCode());
        stockVO.setStorName(stor.getStorName());
//        BatchStock stock = new BatchStock();
//        BeanUtils.copyProperties(stockVO,stock);

        int stockEffectRowCount = 0;
        // 获取批次库存
        BatchStockVO oldStock = stockDAO.getBatchStock(stockVO);
        if (oldStock == null) {
            // 如果库存表里不存在，就新增一条
            stockEffectRowCount = stockDAO.insertBatchStock(stockVO);
        } else {
            stockEffectRowCount = stockDAO.updateBatchStock(stockVO);
        }

        if (stockEffectRowCount <= 0) {
            return 0;
        }

        // 记录批次库存日志
        BatchStockLog batchStockLog = new BatchStockLog();
        batchStockLog.setLogId(java.util.UUID.randomUUID().toString().replace("-", ""));
        BeanUtils.copyProperties(stockVO, batchStockLog);
        int stockLogEffectRowCount = stockDAO.insertBatchStockLog(batchStockLog);

        if (stockLogEffectRowCount <= 0) {
            return 0;
        }
        return 1;
    }

}
